import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Steps, InputNumber, Upload, Input, Calendar, Badge, Empty, Tooltip, Popover, Button, Tabs, Modal, Select, message, Pagination } from 'antd';
import moment from 'moment';
import { PrimaryC, PrimaryGhostC, TableC, FixedButtonC } from '../../../../comps';
import myStyle from '../index.less';
const { Step } = Steps;

@connect(({ survivalManageM, loading }) => ({
  survivalManageM,
  loading,
}))
export default class TotalTransferC extends PureComponent {
  state = {
    stepStatus: 0, //当前步骤
    columns: undefined,
    dataSource: undefined,
  };
  componentDidMount() {
    this.queryAllProduct(); //查询系列产品持仓数据
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    //系列产品id切换更新
    if (nextProps.args && this.props.args && nextProps.args.timestamp != this.props.args.timestamp) {
      this.setState(
        {
          columns: undefined,
          dataSource: undefined,
          stepStatus: 0, //当前步骤
        },
        () => {
          this.queryAllProduct();
        },
      ); //查询系列产品持仓数据
    }
  }

  //根据系列产品ID，获取持仓数据
  queryAllProduct = () => {
    if (!this.props.args) return;
    this.props.dispatch({
      type: 'survivalManageM/queryAllProduct',
      payload: {
        listId: this.props.args.id,
        currentPage: 1,
        numInPage: 50000,
      },
      callback: (data) => {
        if (data) {
          data.dataSource &&
            data.dataSource.map((item) => {
              let sumRate = this.calcRate(item.childData.data.dataSource || []);
              item.originalRate = sumRate;
              item.currentRate = sumRate;
            });
          this.setState({
            columns: data.columns || [],
            dataSource: data.dataSource || [],
          });
        } else {
          this.setState({
            columns: [],
            dataSource: [],
          });
        }
      },
    });
  };
  //计算原始收益率\当前收益率
  calcRate = (arr) => {
    let sumRate = null;
    arr &&
      arr.map((item) => {
        sumRate = (sumRate || 0) + item.assetRate * 1 * (item.weight * 1);
      });
    return sumRate;
  };
  //试算
  tryCalc = () => {
    const { stepStatus, dataSource } = this.state;
    if (!this.props.args) return;
    this.props.dispatch({
      type: 'survivalManageM/totalTransfer',
      payload: {
        listId: this.props.args.id,
      },
      callback: (data) => {
        if (data) {
          //整体转仓的值 更新到表格的子表里
          Object.keys(data).map((productId) => {
            dataSource.map((item) => {
              if (item.id == productId) {
                item.childData.data.dataSource = data[productId]; //替换值
                let sumRate = this.calcRate(data[productId] || []);
                item.currentRate = sumRate; //更新当前收益率 原收益率不变
              }
            });
          });
          this.setState({
            dataSource: [...dataSource],
          });
          this.setState({
            //成功之后 跳转至下一步 上一步文件未做保存
            stepStatus: stepStatus + 1,
          });
        }
      },
    });
  };
  //formAssignData  将入参数据改造下
  formAssignData = (data) => {
    if (!data) return;
    let arr = data.map((item) => {
      return {
        id: item.id,
        allocation: item.allocation * 1,
        price: item.price * 1,
      };
    });
    return arr || [];
  };
  //点击确定转仓
  transfer = () => {
    const { dataSource, stepStatus } = this.state;
    const arr = [];
    dataSource.map((item) => {
      arr.push({
        productId: item.id,
        assignData: this.formAssignData(item.childData.data.dataSource),
      });
    });
    this.props.dispatch({
      type: 'survivalManageM/confirmAdust',
      payload: {
        idList: arr,
      },
      callback: (data) => {
        if (data) {
          this.setState(
            {
              stepStatus: stepStatus + 1,
              columns: undefined,
              dataSource: undefined,
            },
            () => {
              this.queryAllProduct();
            },
          ); //查询系列产品持仓数据
        }
      },
    });
  };
  //渲染子表格
  expandedRowRender = (record) => {
    record.childData.data.columns.map((item) => {
      if (item.key == 'price' || item.key == 'marketValue') {
        item.type = 'money';
        if (item.key == 'price') {
          item.toFixed = 4;
        }
      }
      if (item.key == 'assetRate' || item.key == 'weight') {
        item.type = 'rate';
        if (item.key == 'assetRate') item.toFixed = 4;
      }
      if (item.key == 'allocation') {
        item.type = 'number';
      }
    });
    record.childData.data.dataSource.map((item, key) => {
      item.key = key;
    });
    return (
      <TableC
        columns={record.childData.data.columns || []}
        dataSource={record.childData.data.dataSource || []}
        hidePage={true}
        rowKey='key'
        // width={'1000px'}
      />
    );
  };
  renderTable = () => {
    const { columns, dataSource } = this.state;
    dataSource &&
      dataSource.map((item, key) => {
        item.key = key;
      });
    columns &&
      columns.map((item) => {
        item.width = '25%';
        if (item.key == 'originalRate' || item.key == 'currentRate') {
          item.type = 'rate';
          item.toFixed = 4;
        }
      });
    let offsetHeight = window.offsetHeight || window.innerHeight;
    let height = offsetHeight - 490 < 300 ? 300 : offsetHeight - 490;
    return <TableC columns={columns} dataSource={dataSource} rowKey='key' scroll={{ x: '100%' }} expandedRowRender={this.expandedRowRender} hidePage={true} />;
  };

  render() {
    const { stepStatus, dataSource } = this.state;
    const { loading } = this.props;
    const steps = [
      {
        title: '查看当前持仓',
        content: 'First-content',
      },
      {
        title: '查看转仓信息',
        content: 'Second-content',
      },
      {
        title: '确认转仓',
        content: 'Last-content',
      },
    ];
    return (
      <div>
        <FixedButtonC
          topHtml={
            <>
              <div className={myStyle.stepCls}>
                <div className='stepBg'>
                  <Steps current={stepStatus} items={steps} />
                    {/* {steps.map((item) => (
                      <Step key={item.title} title={item.title} />
                    ))} */}
                  {/* </Steps> */}
                </div>
                {this.renderTable()}
              </div>
            </>
          }
          otherHeight={170}
          bottomHtml={
            <div className={myStyle.borderLine}>
              {stepStatus != 2 && (
                <div>
                  <PrimaryC
                    title={stepStatus == 0 ? '试算' : '确定转仓'}
                    disabled={dataSource ? false : true}
                    loading={loading.effects['survivalManageM/confirmAdust'] === true || loading.effects['survivalManageM/totalTransfer'] === true}
                    onClick={stepStatus == 0 ? this.tryCalc : this.transfer}
                  />
                  <PrimaryGhostC title='返回' onClick={() => this.props.goNext(1)} />
                </div>
              )}
              {stepStatus == 2 && (
                <div className={'backBtn'}>
                  <PrimaryGhostC title='返回' onClick={() => this.props.goNext(1)} />
                </div>
              )}
            </div>

            // <div className='showBtn'>

            // </div>
          }
        ></FixedButtonC>
      </div>
    );
  }
}
